from django.shortcuts import render,redirect,HttpResponse
from App001 import  models
from openpyxl import load_workbook
from django.core.validators import ValidationError
from django.core.validators import RegexValidator
# from App001.views import depart
# Create your views here.
def depart_list(request):
    """部门列表"""
    queryset=models.Department.objects.all()
    return render(request,'depart_list.html',{"queryset":queryset})
def depart_add(request):
    """添加部门"""
    if request.method=="GET":
          return render(request,'depart_add.html')

    title=request.POST.get("title")
    models.Department.objects.create(title=title)
    return redirect("/Class/list/")
def depart_delete(request):
    """删除部门"""
    nid=request.GET.get('nid')
    models.Department.objects.filter(id=nid).delete()
    return redirect("/depart/list/")
def depart_edit(request,nid):
    """编辑部门"""
    #根据nid。来获取他的数据[obj]
    #获取数据库中的第一条数据，然后传到html中进行渲染

 #其实一般都是get是为了显示页面，对于那个post则是为了来读取数据
    if request.method=="GET":
        row_object=models.Department.objects.filter(id=nid).first()
        return render(request,'depart_edit.html',{"row_object":row_object})
    title=request.POST.get("title")
    # 以下是对数据库进行处理
    # 这里的get是为了显示，而那个POSt则是为了进行数据的更改
    models.Department.objects.filter(id=nid).update(title=title)
    return redirect("/depart/list/")
#文件导入上传
def depart_multi(request):
    """批量上传excel文件"""
    #1首先获取文件的对象
    file_objects=request.FILES.get("exc")
    # print(file_objects.name) #获取文件的名字

    #将文件的对象传递给openxl
    wb=load_workbook(file_objects)
    sheet=wb.worksheets[0]
    #循环去获取数据将所有的数据都进行遍历然后来进行数据的存储

    for row in sheet.iter_rows(min_row=2):
        text=row[0].value
        print(text)
        exist=models.Department.objects.filter(title=text).exists()

        if not exist:
            models.Department.objects.create(title=text)

    return redirect("/depart/list/")